import 'dart:typed_data';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_yn_goods/config/app_color.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/loading/loading_utils.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/utils/permisson/permission_utils.dart';
import 'package:flutter_yn_goods/widgets/button/common_button.dart';
import 'package:flutter_yn_goods/widgets/image/image_view.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:screenshot/screenshot.dart';

class WidgetShareDialog extends StatefulWidget {
  const WidgetShareDialog(
      {super.key,
      required this.img,
      required this.title,
      required this.price,
      required this.goodsId,
      this.autoScreenshot = false});

  final String img;
  final String title;
  final String goodsId;
  final String price;

  final bool autoScreenshot;

  Future show() async {
    return await Get.dialog(
      this,
      barrierColor: Colors.black.withOpacity(0.8),
      barrierDismissible: false,
    );
  }

  @override
  State<WidgetShareDialog> createState() => _WidgetShareDialogState();
}

class _WidgetShareDialogState extends State<WidgetShareDialog> {
  ScreenshotController screenshotController = ScreenshotController();

  Future<bool> savePicture() async {
    bool havePermission =
        await PermissionUtils.checkPermission(Permission.photos);

    if (!havePermission) {
      LoadingUtils.showToast(LocaleKeys.no_album_permission.tr);

      return false;
    }

    LoadingUtils.showLoading();

    Uint8List? images = await screenshotController.capture();

    if (images == null) {
      LoadingUtils.showToast(LocaleKeys.app_error.tr);
      LoadingUtils.dismiss();
      return false;
    }
    dynamic result = await ImageGallerySaver.saveImage(images, quality: 100);
    bool isSuccess = false;
    if (result != null) {
      if (result is bool) {
        isSuccess = result;
      }
      if (result is Map) {
        isSuccess = result["isSuccess"] ?? false;
      }
    }
    LoadingUtils.dismiss();
    LoadingUtils.showToast(
        isSuccess ? LocaleKeys.save_success.tr : LocaleKeys.save_failed.tr);
    return isSuccess;
  }

  @override
  Widget build(BuildContext context) {
    final String uid = AppUserManager().uid.toString();
    final String agentPhone = AppUserManager().user.value?.phone ?? '';
    final String formattedPrice = "₫${widget.price}";

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
            width: 300.w,
            // height: 420.w,
            child: Column(
                // mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Screenshot(
                    controller: screenshotController,
                    child: Container(
                      color: Colors.white,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          ImageView(
                            imageUrl: widget.img,
                            width: 330.w,
                            height: 330.w,
                            loadStateHandler: (ExtendedImageState state) {
                              if (widget.autoScreenshot) {
                                if (state.extendedImageLoadState ==
                                    LoadState.completed) {
                                  // LoadingUtils.showLoading();
                                  savePicture().then((value) {
                                    // LoadingUtils.dismiss();
                                    Get.back(result: true);
                                  });
                                }
                              }
                              clog(
                                  'message  ${state.extendedImageLoadState.name}');
                              return null;
                            },
                          ),
                          Padding(
                            padding: EdgeInsets.symmetric(horizontal: 16.w),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Row(),
                                Text(
                                  widget.title,
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      color: AppColor.color282828,
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w500),
                                ),
                                8.verticalSpaceFromWidth,
                                Text(
                                  "${LocaleKeys.price.tr}: $formattedPrice",
                                  style: TextStyle(
                                      color: AppColor.primary,
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w500),
                                ),
                                8.verticalSpaceFromWidth,
                                Text(
                                  "${LocaleKeys.product_id.tr}: ${widget.goodsId}",
                                  style: TextStyle(
                                      color: AppColor.color282828,
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w500),
                                ),
                                8.verticalSpaceFromWidth,
                                Text(
                                  "${LocaleKeys.agent_id.tr}: $uid",
                                  style: TextStyle(
                                      color: AppColor.color282828,
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w500),
                                ),

                                8.verticalSpaceFromWidth,
                                Text(
                                  "${LocaleKeys.agent_contact.tr}: $agentPhone",
                                  style: TextStyle(
                                      color: AppColor.color282828,
                                      fontSize: 14.sp,
                                      fontWeight: FontWeight.w500),
                                ),
                                // 8.verticalSpaceFromWidth,
                              ],
                            ),
                          ),
                          12.verticalSpaceFromWidth,
                        ],
                      ),
                    ),
                  ),
                  Visibility(
                      visible: widget.autoScreenshot == false,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          32.verticalSpaceFromWidth,
                          CommonButton.expend(
                            width: 330.w,
                            title: LocaleKeys.save_to_gallery.tr,
                            onClick: () {
                              savePicture();
                            },
                          ),
                          16.verticalSpaceFromWidth,
                          CommonButton.expend(
                            width: 330.w,
                            title: LocaleKeys.cancel.tr,
                            backgroundColor: Colors.lightBlue,
                            onClick: () {
                              Get.back();
                            },
                          ),
                        ],
                      )),
                ]))
      ],
    );
  }
}

// class WidgetShareDialog extends StatelessWidget {
//   const WidgetShareDialog({super.key, required this.img, required this.title});
//
//   final String img;
//   final String title;
//
//   show() {
//     Get.dialog(
//       this,
//       barrierColor: Colors.black.withOpacity(0.8),
//       barrierDismissible: false,
//     );
//   }
//
//   @override
//   Widget build(BuildContext context) {
//     return
//   }
// }
